<template>
  <div class="webrtc-container">
    <div class="video-container">
      <video ref="videoElement" autoplay playsinline muted @dblclick="toggleFullscreen"></video>
      <button @click="goToConfig" class="config-btn">
        <i class="fas fa-cog"></i>
      </button>
    </div>
    <div v-if="error" class="error">{{ error }}</div>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted } from 'vue'
import { useRouter } from 'vue-router'

const router = useRouter()

const videoElement = ref(null)
const webrtcPeerConnection = ref(null)
const websocket = ref(null)
const isConnected = ref(false)
const error = ref('')

const configuration = {
  iceServers: [
    { urls: 'stun:stun.l.google.com:19302' }
  ]
}

const connectWebSocket = () => {
  const wsProtocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:'
  const wsHost = window.location.hostname
  
  // 获取登录时存储的token
  const token = localStorage.getItem('access_token')
  if (!token) {
    error.value = '未登录或token已过期'
    router.push('/login')
    return
  }

  // 检查token是否过期
  const tokenExpires = localStorage.getItem('token_expires')
  if (tokenExpires && parseInt(tokenExpires) < Date.now()) {
    error.value = 'token已过期，请重新登录'
    router.push('/login')
    return
  }

  // 通过URL参数传递token
  const wsUrl = `${wsProtocol}//${wsHost}/v1/webrtc?token=${encodeURIComponent(token)}`
  websocket.value = new WebSocket(wsUrl)

  websocket.value.onopen = () => {
    console.log('WebSocket connected')
    setupWebRTC()
  }

  websocket.value.onmessage = async (event) => {
    try {
      const message = JSON.parse(event.data)
      handleSignalingMessage(message)
    } catch (err) {
      console.error('Failed to parse message:', err)
    }
  }

  websocket.value.onerror = (error) => {
    console.error('WebSocket error:', error)
    error.value = 'WebSocket连接错误'
  }

  websocket.value.onclose = (event) => {
    console.log('WebSocket disconnected', event)
    isConnected.value = false
    
    // 处理各种关闭原因
    if (event.code === 1008) { // 策略关闭，通常是认证失败
      error.value = '认证失败，请重新登录'
      localStorage.clear();  // 清除所有认证信息
      router.push('/login')
    } else if (event.code === 1006) { // 异常关闭
      error.value = '连接断开，可能是设备重启，请重新登录'
      localStorage.clear();  // 清除所有认证信息
      router.push('/login')
    } else {
      error.value = '连接断开，请刷新页面重试'
      // 如果是其他原因导致的断开，可以尝试重连
      setTimeout(connectWebSocket, 5000)
    }
  }
}

const setupWebRTC = async () => {
  try {
    webrtcPeerConnection.value = new RTCPeerConnection(configuration)

    webrtcPeerConnection.value.ontrack = (event) => {
      if (videoElement.value && event.streams[0]) {
        videoElement.value.srcObject = event.streams[0]
        videoElement.value.play().catch(console.warn)
      }
    }

    webrtcPeerConnection.value.onicecandidate = ({ candidate }) => {
      if (candidate) {
        sendMessage({ ice: candidate });
      }
    };

    // 添加视频转码器
    webrtcPeerConnection.value.addTransceiver('video', {
      direction: 'recvonly',
      streams: [new MediaStream()]
    })

    isConnected.value = true
  } catch (err) {
    console.error('Error in setupWebRTC:', err)
    error.value = `WebRTC setup failed: ${err.message}`
  }
}

const handleSignalingMessage = async (message) => {
  try {
    console.log('Received signaling message:', message.type)

    if (message.sdp) {
      console.log('Setting remote description...')
      await webrtcPeerConnection.value.setRemoteDescription(
        new RTCSessionDescription({
          type: message.type,
          sdp: message.sdp
        })
      )

      if (message.type === 'offer') {
        console.log('Creating answer...')
        const answer = await webrtcPeerConnection.value.createAnswer()
        console.log('Setting local description (answer)...')
        await webrtcPeerConnection.value.setLocalDescription(answer)
        console.log('Sending answer...')
        sendMessage({
          type: 'answer',
          sdp: answer.sdp
        })
      }
    } else if (message.candidate) {
      console.log('Adding ICE candidate...')
      await webrtcPeerConnection.value.addIceCandidate(
        new RTCIceCandidate({
          candidate: message.candidate,
          sdpMLineIndex: message.sdpMLineIndex
        })
      )
    }
  } catch (err) {
    console.error('Error handling signaling message:', err)
    error.value = 'Error in WebRTC signaling'
  }
}

const sendMessage = (message) => {
  if (websocket.value && websocket.value.readyState === WebSocket.OPEN) {
    websocket.value.send(JSON.stringify(message))
  }
}

const goToConfig = () => {
  router.push('/config')
}

// 添加全屏切换功能
const toggleFullscreen = async () => {
  try {
    if (!document.fullscreenElement) {
      await videoElement.value.requestFullscreen()
    } else {
      await document.exitFullscreen()
    }
  } catch (err) {
    error.value = '全屏切换失败: ' + err.message
  }
}

onMounted(() => {
  connectWebSocket()
})

onUnmounted(() => {
  if (webrtcPeerConnection.value) {
    webrtcPeerConnection.value.close()
    webrtcPeerConnection.value = null
  }
  if (websocket.value) {
    websocket.value.close()
    websocket.value = null
  }
  isConnected.value = false
})
</script>

<style scoped>
.webrtc-container {
  width: 100vw;
  height: 100vh;
  margin: 0;
  padding: 0;
  position: relative;
  overflow: hidden;
}

.video-container {
  position: relative;
  width: 100%;
  height: 100%;
  background: #000;
  margin: 0;
  overflow: hidden;
}

.video-container:hover .config-btn {
  opacity: 1;
}

.config-btn {
  position: absolute;
  top: 20px;
  right: 20px;
  padding: 8px;
  border: none;
  border-radius: 50%;
  background: rgba(0, 0, 0, 0.5);
  color: white;
  cursor: pointer;
  font-size: 16px;
  transition: all 0.3s;
  opacity: 0;
  z-index: 1000;
  width: 36px;
  height: 36px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.config-btn:hover {
  background: rgba(0, 0, 0, 0.7);
  transform: rotate(30deg);
}

video {
  width: 100%;
  height: 100%;
  object-fit: cover;
  display: block;
}

.error {
  position: absolute;
  top: 20px;
  left: 50%;
  transform: translateX(-50%);
  color: #f44336;
  background: rgba(0, 0, 0, 0.7);
  padding: 10px 20px;
  border-radius: 4px;
  z-index: 1000;
}
</style>
